<!-- 
 * Copyright (c) 2021-2025 申菱环境 All Rights Reserved
 * 项目名称：申菱物联平台
 * 模块名称：消息管理
 * 功能名称：消息首页
 * author : huzhiqi
 * date   : 2022/7/14 10:20
 -->
<template>
  <TablePage>
    <template #top>
      <SearchForm
        :title="t('routes.messageManage')"
        :add-btn-text="t('aiot.message.addNotifi')"
        :del-btn-text="t('common.delete')"
        :del-btn-props="{
          disabled: selectedRowKeys.length === 0,
          onClick: delMsgFn,
        }"
        :keyword-search-data="searchModel"
        :select-data="selectData"
        :add-btn-oper-type="OperPermissionType.MANAGE"
        @add="showCreateModal"
        @search="handleSearch"
      >
      </SearchForm>
    </template>
    <SlTable
      :columns="columns"
      row-key="notificationId"
      :data-source="tableData"
      :loading="tableLoading"
      :pagination="pagination"
      :search-model="applySearchModel"
      :row-selection="{
        type: 'checkbox',
        selectedRowKeys,
        onChange: (keys) => {
          selectedRowKeys = keys;
        },
      }"
    >
      <template #bodyCell="{ column, record }">
        <div v-if="column.dataIndex === 'state'">
          <a-tag class="sl-tag !mr-2 !mb-2" :color="record.state === 'SENDING' ? 'warning' : 'success'">
            {{ getLabelByValueFromEnum(record.state, MessageState, "messageState") }}
          </a-tag>
          <!-- {{ getLabelByValueFromEnum(record.state, MessageState, "messageState") }} -->
        </div>
        <div v-if="column.dataIndex === 'businessType'">
          {{ getLabelByValueFromEnum(record.businessType, BusinessType, "businessType") || "--" }}
        </div>
        <div v-if="column.dataIndex === 'noticeType'" :style="{ width: '60px' }">
          {{ getLabelByValueFromEnum(record.noticeType, MessageType, "messageType") }}
        </div>
        <EllipsisText v-if="column.dataIndex === 'content'" :max-len="50" :text="record.content" />
        <div v-if="column.dataIndex === 'isRead'" :style="{ width: '80px' }">
          {{ record.isRead ? "是" : "否" }}
        </div>
        <a-space v-if="column.key === 'oper'">
          <PermissionBtn
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="showUpdateModal(record)"
            >{{ t("common.edit") }}</PermissionBtn
          >
          <DropdownOper v-model:visible="record.operVisible" :record="record" :data="operData"> </DropdownOper>
        </a-space>
        <a
          v-if="column.dataIndex === 'title'"
          href="javascript:void(0)"
          @click="setShowOptions({ action: CURDAction.CHECK, record })"
        >
          <EllipsisText :max-len="12" :text="record.title" />
        </a>
      </template>
    </SlTable>
    <CreateNotifiModal
      v-model:visible="createVisible"
      :model="notifiModel"
      :model-form-setting="modelFormSetting"
      @create="reloadTable"
    />
    <CURDDialog
      id-key="notificationId"
      :model="notifiModel"
      :delete-message="t('aiot.message.delMsg')"
      :show-options="showOptions"
      :check-title="t('aiot.message.msgDetail')"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :oper-data="operData"
      :curd="curd"
      :reload-table="reloadTable"
      @before-ok="functionBeforeOk"
      @before-show="beforeShow"
    />
  </TablePage>
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { Api, sendNotifications, recoverNotifications } from "/@/api/aiot/message";
import SearchForm from "/@/components/SearchForm.vue";
import { useCURD } from "/@/hooks/useCURD";
import { OperPermissionType } from "/@/api/aiot/role/models";
import PermissionBtn from "/@/components/PermissionBtn.vue";
import { enumToOptions, getLabelByValueFromEnum } from "/@/utils/common";
import EllipsisText from "/@/components/common/EllipsisText.vue";
import DropdownOper from "/@/components/DropdownOper.vue";
import {
  CURDAction,
  CURDModalEvent,
  FormItemComponentType,
  FormItemData,
  OperItem,
  ShowCURDModalOptions,
} from "/@/components/CURDDialog/models";
import { PatternKey } from "/@/utils/verify";
import TablePage from "/@/components/TablePage.vue";
import SlTable from "/@/components/SlTable.vue";
import CreateNotifiModal from "./CreateNotifiModal.vue";
import { BusinessType, FormAddItem, MessageType, MessageState, NotifiItem } from "/@/api/aiot/message/models";
import { PermissionCode } from "/@/api/permissionCode";
import InfoModal from "../../InfoModal";
import { message } from "ant-design-vue";
import { SelectItem } from "/@/types/components";
import { OrderRule } from "/@/api/models";

const { t } = useI18n();
const createVisible = ref<boolean>(false);
const selectedRowKeys = ref<string[]>([]);
const operVisible = ref<boolean>(false);
const selectData = ref<SelectItem[]>([
  {
    label: t("aiot.message.businessType"),
    value: "",
    key: "businessType",
    props: { allowClear: true },
    options: enumToOptions(BusinessType, "businessType"),
  },
  {
    label: t("aiot.message.messageType"),
    value: "",
    key: "noticeType",
    props: { allowClear: true },
    options: enumToOptions(MessageType, "messageType"),
  },
  {
    label: t("aiot.message.state"),
    value: "",
    props: { allowClear: true },
    key: "state",
    options: enumToOptions(MessageState, "messageState"),
  },
]);
const notifiModel = ref<FormAddItem>({
  title: "",
  content: "",
  businessType: "SYS_NOTICE",
  noticeType: "NOTIFY",
  state: "",
});
const modelFormSetting: FormItemData[] = [
  {
    key: "title",
    label: t("aiot.message.title"),
    max: 32,
    required: true,
  },
  {
    key: "businessType",
    label: t("aiot.message.businessType"),
    max: 32,
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: enumToOptions(BusinessType, "businessType"),
    },
  },
  {
    key: "noticeType",
    label: t("aiot.message.messageType"),
    max: 32,
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: enumToOptions(MessageType, "messageType"),
    },
  },
  {
    label: t("aiot.message.content"),
    key: "content",
    required: true,
    max: 250,
    type: FormItemComponentType.TEXTAREA,
  },
  {
    key: "state",
    hide: true,
  },
];
const columns = [
  {
    title: t("aiot.message.title"),
    dataIndex: "title",
    width: 160,
  },
  {
    title: t("aiot.message.author"),
    dataIndex: "author",
    width: 120,
  },
  {
    title: t("aiot.message.businessType"),
    dataIndex: "businessType",
    width: 120,
  },
  {
    title: t("aiot.message.content"),
    dataIndex: "content",
  },
  {
    title: t("aiot.message.createOn"),
    dataIndex: "createOn",
    width: 120,
  },
  {
    title: t("aiot.message.isRead"),
    dataIndex: "isRead",
    width: 100,
  },
  {
    title: t("aiot.message.massgeType"),
    dataIndex: "noticeType",
    width: 120,
  },
  {
    title: t("aiot.message.sendOn"),
    dataIndex: "sendOn",
  },
  {
    title: t("aiot.message.state"),
    dataIndex: "state",
    width: 100,
  },
  {
    title: t("common.oper"),
    key: "oper",
    fixed: "right",
    width: 120,
  },
];
function setShowOptions(options: ShowCURDModalOptions) {
  showOptions.value = options;
}
// 删除多个msg
function delMsgFn() {
  showOptions.value = { action: CURDAction.DELETE, ids: selectedRowKeys.value, message: t("aiot.message.delMsgs") };
}
const showOptions = ref<ShowCURDModalOptions>();
function showCreateModal() {
  // showOptions.value = { action: CURDAction.CREATE };
  createVisible.value = true;
}
function beforeShow(e) {
  if (e.action === CURDAction.UPDATE || e.action === CURDAction.CHECK) {
  }
}
const searchModel = [{ key: "searchText", label: "标题" }];
function handleSearch(model) {
  reloadTable({ model, current: 1 });
}
const {
  tableData,
  tableLoading,
  curd,
  reloadTable,
  pagination,
  searchModel: applySearchModel,
} = useCURD<NotifiItem>({
  createUrl: Api.addNotifications,
  deleteUrl: Api.deleteNotificationsByIds,
  getPageUrl: Api.getMessagePage,
  updateUrl: Api.updateNotifications,
});

const operData: OperItem<NotifiItem>[] = [
  {
    label: t("common.edit"),
    handler: showUpdateModal,
    operType: OperPermissionType.MANAGE,
    // permissionCode: PermissionCode.USER_UPDATE,
  },
  {
    label: t("common.delete"),
    type: "primary",
    // permissionCode: PermissionCode.USER_DELETE,
    operType: OperPermissionType.MANAGE,
    danger: true,
    disabledMes: (record) => (record.state === "SENDED" ? t("aiot.message.beforeDelMsg") : ""),
    handler: deleteRecord,
  },
  {
    label: (record) => {
      return record.state === "SENDING" ? t("aiot.message.publish") : t("aiot.message.unSend");
    },
    type: "primary",
    // permissionCode: PermissionCode.USER_UPDATE,
    operType: OperPermissionType.MANAGE,
    async handler(record: NotifiItem) {
      InfoModal.info({
        content: record.state === "SENDING" ? t("aiot.message.sendMsg") : t("aiot.message.unSendMsg"),
        async onOk() {
          let result: boolean | null;
          if (record.state === "SENDING") {
            result = await sendNotifications({ notificationsId: record.notificationId });
          } else {
            result = await recoverNotifications({ notificationsId: record.notificationId });
          }
          if (result) {
            message.success(t("common.operSuccess"));
            await reloadTable();
          }
        },
      });
    },
  },
];
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function deleteRecord(record) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
function functionBeforeOk(e: CURDModalEvent) {
  if (e.model) {
    const model = e.model as NotifiItem;
    if (e.action === CURDAction.CREATE) {
      // model.parentIndustryInnerId = 0;
    }
  }
}
</script>
